var lottery = {
  index: -1, //当前转动到哪个位置，起点位置

  count: 0, //总共有多少个位置

  timer: 0, //setTimeout的ID，用clearTimeout清除

  speed: 100, //初始转动速度

  times: 0, //转动次数

  cycle: 50, //转动基本次数：即至少需要转动多少次再进入抽奖环节

  prize: -1, //中奖位置

  init: function (id) {
    if ($("#" + id).find(".lottery-unit").length > 0) {
      $lottery = $("#" + id);

      $units = $lottery.find(".lottery-unit");

      this.obj = $lottery;

      this.count = $units.length;

      $lottery.find(".lottery-unit-" + this.index).addClass("on");
    }
  },

  roll: function () {
    var index = this.index;

    var count = this.count;

    var lottery = this.obj;

    $(lottery)
      .find(".lottery-unit-" + index)
      .removeClass("on");

    index += 1;

    if (index > count - 1) {
      index = 0;
    }

    $(lottery)
      .find(".lottery-unit-" + index)
      .addClass("on");

    this.index = index;

    return false;
  },

  stop: function (index) {
    this.prize = index;

    return false;
  },

  // 动画停止，回调
  callback: function () {
    $('.lottery-get-wrapper').css('z-index', 10000).show();
    $('.mask2').show()
  }
};

function roll() {
  lottery.times += 1;

  lottery.roll();

  // 动画停止
  if (lottery.times > lottery.cycle + 10 && lottery.prize == lottery.index) {
    clearTimeout(lottery.timer);

    lottery.prize = -1;

    lottery.times = 0;

    lotteryRolling = false;

    lottery.callback();
  } else {
    if (lottery.times < lottery.cycle) {
      lottery.speed -= 10;
    } else if (lottery.times == lottery.cycle) {
      var index = (Math.random() * lottery.count) | 0;

      lottery.prize = index;
    } else {
      if (
        lottery.times > lottery.cycle + 10 &&
        ((lottery.prize == 0 && lottery.index == 7) ||
          lottery.prize == lottery.index + 1)
      ) {
        lottery.speed += 110;
      } else {
        lottery.speed += 20;
      }
    }

    if (lottery.speed < 40) {
      lottery.speed = 40;
    }
    lottery.timer = setTimeout(roll, lottery.speed);
  }

  return false;
}

var lotteryRolling = false;
$(function () {
  lottery.init("lottery");

  $("#lottery .begin").click(function () {
    if (lotteryRolling) {
      return false;
    } else {
      var time = parseInt($("#lottery .time").text());

      // 没有抽奖次数
      if (time <= 0) {
        iosOverlay({
          text: "今日抽奖次数已用完",
          duration: 2000,
          icon: "img/check.png"
        });
        return;
      }

      // 次数减一
      time -= 1;
      $("#lottery .time").text(time);

      lottery.speed = 150;

      roll();

      lotteryRolling = true;

      return false;
    }
  });
});